<script setup>
import {ref, reactive} from 'vue'
import { getNoticeDetail, updateSysNoticeReply, sysNoticeReply, sysNoticeReplyList } from "@/api/notice";
import UniFilePicker from "@/uni_modules/uni-file-picker/components/uni-file-picker/uni-file-picker.vue"
import {onLoad} from "@dcloudio/uni-app";
import {baseUrl, host} from "@/utils/config"
import { uploadUrl } from "@/api";

const pageData = reactive({
  formData: {},
  submitData: {},
  replyData: {}
})
const attfileUrl = ref('')
const content = ref('')
const visible = ref(false)
const fileType = ref(false)
const contentShow = ref(false)
const userInfo = uni.getStorageSync('userInfo')

const loadingBtn = ref(false)
const defaultFileList = ref([])

const detailId = ref('')
const loading = ref(false)
onLoad((options) => {
  if(options.id) {
    detailId.value = options.id
    getDetail(detailId.value)
    getReplyList()
    return
  }
})

const substrFun = (str)  => {
  return str?.substring(0, 10)
}
const getDetail = async(id) => {
  loading.value = true
  await getNoticeDetail(id).then(res => {
    pageData.formData = res.data    
    const html = pageData.formData.noticeContent;
    const html_new = html.replace(/<img/g, '<img style="width:100%"')
    const regex = /(<img[^>]+src=["'])(\/api\/profile[^"']*["'])/g;
    const newHtml = html_new.replace(regex, (match, p1, p2) => {
        return `${p1}${host}${p2}`; 
    });
    
    //图片链接处理
    pageData.formData.noticeContent = newHtml
    // pageData.formData.noticeContent
    //   .replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
    //     return '<img  src="' + (host + capture) + '" style="max-width: 100%;margin: 0 auto;" />';
    //   });
  
    
    loading.value = false
  })
}
const baseClick = () => {
  console.log('点击签到')
  visible.value = true
}
// 确定签到
const clickOk = () => {
  console.log('event ok')
  pageData.submitData = {
    noticeId: detailId.value,
    userId: userInfo.userId,
    deptId: userInfo.deptId,
    sign: 1
  }
  let api = ''
  if(pageData.replyData.id){
    pageData.submitData.id = pageData.replyData.id
    api = updateSysNoticeReply
  }else{
    api = sysNoticeReply
  }
  console.log(pageData.submitData)
  api(pageData.submitData).then(res => {
    getReplyList()
    uni.showToast({
      title: msg
    })
  }).catch(err => {
  })
}
const showReply = () => {
  contentShow.value = true
  if(pageData.replyData.id){
    content.value = pageData.replyData.content
    let name = matchAnnexname(pageData.replyData.attfile)
    defaultFileList.value = [{
      "name": name,
      "extname":name.substring(pageData.replyData.attfile.lastIndexOf('.') + 1).toLowerCase(),
      "url":pageData.replyData.attfile,
    }]
    attfileUrl.value = pageData.replyData.attfile;
  }
}
// 获取回复列表
const getReplyList = () => {
  const params = {
    userId: userInfo.userId,
    deptId: userInfo.deptId,
    noticeId: detailId.value
  }
  sysNoticeReplyList(params).then(res => {
    if(res.rows.length){
       pageData.replyData = res.rows[0]
       fileType.value = getFileType(pageData.replyData.attfile)
    }
    
  })
}
// 提交回复
const submitContent = () =>{
  pageData.submitData = {
    noticeId: detailId.value,
    userId: userInfo.userId,
    deptId: userInfo.deptId,
    content: content.value,
    attfile: attfileUrl.value
  }
  let api = ''
  if(pageData.replyData.id){
    pageData.submitData.id = pageData.replyData.id
    api = updateSysNoticeReply
  }else{
    api = sysNoticeReply
  }
  console.log(pageData.submitData)
  if(!pageData.submitData.content && !pageData.submitData.attfile){
    uni.showToast({
      title: '内容不能为空',
      icon: 'none'
    })
    return
  }
  api(pageData.submitData).then(res => {
    getReplyList()
    uni.showToast({
      title: '提交成功'
    })
    contentShow.value = false
  }).catch(err => {
  })
}
// 获取上传状态
const select = (e) =>{
    console.log('选择文件：',e)
    uni.uploadFile({
      url: uploadUrl, //上传图片的后端接口
      filePath: e.tempFilePaths[0],
      name: 'file',
      success: res => {
        // console.log('rrrrrrrrr', res, res.data)
        const fileData = JSON.parse(res.data)
        attfileUrl.value = fileData.fileName;
        if(JSON.parse(res.data).code !== 200) {
          uni.showToast({
            title: res.msg
          })
          return
        }
      }
  })
}
  
// 上传成功
const success = (e) =>{
  console.log('上传成功')
}

// 上传失败
const fail = (e) =>{
  console.log('上传失败：',e)
  uni.showToast({
    title: '上传失败'
  })
}
// 删除附件
const deleteFile = (e) =>{
  console.log(e)
  attfileUrl.value = ''
}
// 提取附件名称
const matchAnnexname = (str) => { 
  if (!str) return
  let index = str.lastIndexOf("\/");
  return str.substring(index + 1, str.length);
}
//判断附件类型
const getFileType = (filename) => { 
  let ext = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
  return (ext === 'jpg' || ext === 'jpeg' || ext === 'png' || ext === 'gif');
}
// 附件预览
const previewDocx = (fileUrl) => { 
  uni.downloadFile({
    url: host + fileUrl,
    success: (res) => {
      console.log(res)
      if (res.statusCode === 200) {
        uni.openDocument({
          filePath: res.tempFilePath,
          // 如果文件名包含中文，建议使用escape(res.tempFilePath)转码，防止ios和安卓客户端导致的差异
          success: function(res) {
            console.log('打开成功')
          }
        });
      }
    }
  })
}
</script>

<template>
  <view class="uni-view">
    <view class="uni-header">{{pageData.formData.noticeTitle}}</view>
    <view class="uni-time">有效期：{{substrFun(pageData.formData.startTime)}}至{{substrFun(pageData.formData.endTime)}}</view>
    <view class="uni-content" v-html="pageData.formData.noticeContent"></view>
    <view class="reply">
      <nut-button v-if="pageData.replyData.sign == 1" type="success">已签到</nut-button>&nbsp;
      <nut-button v-if="pageData.replyData.sign == null || pageData.replyData.sign == '0'" plain type="warning" @click="baseClick" style="margin-right: 10px;">签到</nut-button>&nbsp;
      <nut-button plain type="info" @click="showReply">{{pageData.replyData.id ?'评论':'评论'}}</nut-button>
    </view>
    <nut-dialog
      teleport="#app"
      title="提示"
      content="确定要签到？"
      :onOk="clickOk"
      v-model:visible="visible">
    </nut-dialog>
    <view class="reply_list" v-show="!contentShow">
      <view v-if="pageData.replyData.id"><p>内容：</p> 
        {{ pageData.replyData.content }}</view>
      <view v-if="pageData.replyData.id"><p>附件：</p>
        <image v-if="fileType" style="width: 200px; height: 200px; background-color: #eeeeee;" :src="host+pageData.replyData.attfile"></image>
        <view v-else class="details-content-annex" @click="previewDocx(pageData.replyData.attfile)">{{ matchAnnexname(pageData.replyData.attfile) }}</view>
      </view>
    </view>
    <view class="reply_content" v-show="contentShow">
      <nut-textarea class="text" v-model="content" placeholder="请输入内容"/>
      <uni-file-picker
        v-model="defaultFileList" 
        file-mediatype="all"
        :limit="1"
        file-extname="zip,doc,docx,pdf,pptx,ppt,xlsx,xls,rar" 
        mode="list"
        @select="select" 
        @success="success" 
        @fail="fail"
        @delete="deleteFile"
      />
      <view style="padding: 6px 0;">支持类型:zip,doc,docx,pdf,pptx,ppt,xlsx,xls,rar</view>
      <nut-button type="success" block size="medium" @click="submitContent">提交</nut-button>
    </view>
  </view>
</template>

<style scoped lang="scss">
.uni-view{
  padding: 20px 10px;
}
.uni-header{  
  font-size: 18px;
  text-align: center;
}
.uni-time{
  margin: 10px;
  text-align: right;
}
.uni-content{
  line-height: 1.5;
  word-break: break-all;
}
.reply{
  float: right;
  margin-top: 20px;
}
.reply_content{
  margin-top: 20px;
  border: 1px solid #ccc;
  border-radius: 4px;
  float: left;
  width: 94%;
  margin-bottom: 30px;
  padding: 3%;
}
.reply_list{
  width: 94%;
  float: left;
  margin-top: 20px;
  border: 1px solid #eee;
  border-radius: 10px;
  padding: 10px 10px 30px;
}
.details-content-annex {
  margin-top: 20px;
  font-size: 14px;
  color: #6585FC;
  word-break: break-all;
}
</style>
